import time
import logging

logger = logging.getLogger(__name__)


class RequestTimeMiddleware:
    """
    中间件：统计每个请求的请求耗时
    """

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # 记录请求开始时间
        start_time = time.time()

        # 处理请求
        response = self.get_response(request)

        # 计算耗时
        duration = time.time() - start_time

        # 记录请求路径和耗时（毫秒）
        duration_ms = duration * 1000
        logger.info(f"请求路径: {request.path}, 耗时: {duration_ms:.2f}ms")

        # 在响应头中添加请求耗时信息（调试用）
        response['X-Request-Time'] = f"{duration_ms:.2f}ms"

        return response